package com.kevin.file.service;

import com.kevin.file.feign.FileFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.nio.file.Files;

/**
 * @author Hank Lau
 * @date 2021/11/3
 */
@Slf4j
@Service
public class FileService {

    @Resource
    FileFeign fileFeign;

    public void uploadFile() {
        InputStream input = null;
        OutputStream os = null;
        try {
            File testFile = new File("/Users/yekongle/PDF/English/625words.pdf");

            FileItem fileItem = new DiskFileItem("file", Files.probeContentType(testFile.toPath()), false,
                    testFile.getName(), (int) testFile.length(), testFile.getParentFile());
            input = new FileInputStream(testFile);
            os = fileItem.getOutputStream();
            IOUtils.copy(input, os);
            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
            String resultString = fileFeign.fileUpload(multipartFile);
            log.info("Response: " + resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (input != null) {
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
